﻿using System;
using System.Collections.Generic;
using System.Linq;
using Citi.RoutineBase;
using System.Configuration;
using System.IO;
using Citi.ResourceConsolidation.SchedulerUI.EmailSenderWcf;
using Citi.Helpers;

namespace Citi.ResourceConsolidation.SchedulerUI.RH
{
    public class RHExtractEmail : IExecutableRoutine
    {
        private string ConnectionStringResource { get { return ConfigurationManager.ConnectionStrings[""].ConnectionString; } }
        private string PathExcel { get { return ConfigurationManager.AppSettings["PathExcel"]; } }
        private string PathInput { get { return ConfigurationManager.AppSettings["PathInput"]; } }
        private string EmailSubject { get { return ConfigurationManager.AppSettings["EmailSubject"]; } }
        private string PartialFileName { get { return ConfigurationManager.AppSettings["PartialFileName"]; } }

        public IEnumerable<RoutineParameter> Parameters
        {
            get { throw new NotImplementedException(); }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            throw new NotImplementedException();
        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var networkUser = parameters["RobotUsername"].ToString();
            var networkPassword = parameters["RobotPassword"].ToString();
            var userNotFoundEmail = parameters["UserNotFoundEmails"].ToString();

            DownloadAttachments(currentAction, networkUser, networkPassword);

            var filesToRead = new DirectoryInfo(PathExcel).GetFiles().Where(x => x.Name.Contains(PartialFileName)
                                && (x.Extension == ".xls" || x.Extension == ".xlsx")).Select(x => x.FullName);

            if (!filesToRead.Any())
            {
                currentAction.Description = "No e-mail was found. The RHNEMS routine was marked as executed.";
                return;
            }

            currentAction.Description = string.Format("Was found {0} e-mail with the subject: '{1}'.", filesToRead.Count(), EmailSubject);
            currentAction.Description = string.Format("Reading file {0}.", filesToRead);
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            throw new NotImplementedException();
        }

        private void DownloadAttachments(ICurrentAction currentAction, string networkUser, string networkPassword)
        {
            currentAction.Description = "Looking for Inbox mail.";
            string path = string.Empty;

            using (var client = new EmailClient())
            {
                client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

                var attachment = new DownloadAttachment
                {
                    ApplicationName = "RHNEMS",
                    //DefaultFolder = EmailHelperDefaultFolders.Inbox,
                    InitialDate = DateTime.Today.AddDays(-3),
                    Subject = EmailSubject
                };

                path = client.DownloadAttachment(attachment);
            }

            if (path == null) return;

            var serverName = path.Split(new[] { "/", @"\\", @"\" }, StringSplitOptions.RemoveEmptyEntries).First();

            using (NetworkShareAccesser.Access(serverName, networkUser, networkPassword))
            {
                var downloadedFiles = Directory.GetFiles(path);

                foreach (var file in downloadedFiles.Where(x => Path.GetExtension(x) == ".zip"))
                {
                    if (!Directory.Exists(PathExcel))
                        Directory.CreateDirectory(PathExcel);

                    FileHelper.Decompress(file, PathExcel);
                    File.Delete(file);
                }
            }
        }
    }
}
